package com.lzc.util.translate;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzc.util.translate.dto.BaiduTransResponse;

public class TransApi {
    private static final String TRANS_API_HOST = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    /**
     * 返回对象形式的翻译结果（仅成功结果）。
     * 若返回为错误结构或解析失败，返回 null。
     */
    public BaiduTransResponse getTransResultObject(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        String json = HttpGet.get(TRANS_API_HOST, params);
        try {
            // 先判断是否是错误结构（包含 error_code）
            JsonNode root = OBJECT_MAPPER.readTree(json);
            if (root.has("error_code")) {
                return null;
            }
            return OBJECT_MAPPER.readValue(json, BaiduTransResponse.class);
        } catch (Exception e) {
            return null;
        }
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
